home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_01 / allison / search.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-02  |  1.2 KB  |  61 lines

  1. LISTING 8 - Searches a sorted array of records with the bsearch function
  2.  
  3. /* search.c */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7.  
  8. struct person
  9. {
  10.     char last[16];
  11.     char first[11];
  12.     char phone[13];
  13.     int age;
  14. };
  15.  
  16. static int comp(const void *, const void *);
  17.  
  18. main()
  19. {
  20.     int i;
  21.     struct person *p;
  22.     static struct person key = {"","","555-1965",0};
  23.     static struct person people[] =
  24.       {{"Ford","Henry","555-1903",98},
  25.        {"Lincoln","Abraham","555-1865",161},
  26.        {"Ford","Edsel","555-1965",53},
  27.        {"Trump","Donald","555-1988",49}};
  28.  
  29.     /* Sort */
  30.     qsort(people, 4, sizeof people[0], comp);
  31.  
  32.     /* Search */
  33.     p = bsearch(&key, people, 4, sizeof people[0], comp);
  34.     if (p != NULL)
  35.     {
  36.         printf(
  37.                "%s, %s, %s, %d\n",
  38.                p->last,
  39.                p->first,
  40.                p->phone,
  41.                p->age
  42.               );
  43.     }
  44.     else
  45.         puts("Not found");
  46.     return 0;
  47. }
  48.  
  49. /* Compare function: */
  50. static int comp(const void *x, const void *y)
  51. {
  52.     struct person *p1 = (struct person *) x;
  53.     struct person *p2 = (struct person *) y;
  54.  
  55.     return strcmp(p1->phone,p2->phone);
  56. }
  57.  
  58. /* Output: */
  59. Ford, Edsel, 555-1965, 53
  60.  
  61.